package com.jxauaia.contest.AI;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Component
public class OkHttpAIClient {
    private static final Logger logger = LoggerFactory.getLogger(OkHttpAIClient.class);

    @Value("${ai.spark.appid:default_appid}")
    private String appId;
    @Value("${ai.spark.api-key:default_api_key}")
    private String apiKey;
    @Value("${ai.spark.api-secret:default_api_secret}")
    private String apiSecret;
    @Value("${ai.spark.timeout:30}")
    private int timeout;
    @Value("${ai.spark.api-url:wss://spark-api.xf-yun.com/v3.1/chat}")
    private String apiUrl;

    public String askQuestion(String question, String userId) {
        logger.info("开始处理AI问题，用户ID: {}", userId);

        try {
            String authUrl = getAuthUrl(apiUrl, apiKey, apiSecret);
            String wsUrl = authUrl.replace("http://", "ws://").replace("https://", "wss://");
            logger.debug("WebSocket URL: {}", wsUrl);

            OkHttpClient client = new OkHttpClient.Builder()
                    .pingInterval(10, TimeUnit.SECONDS)
                    .readTimeout(timeout, TimeUnit.SECONDS)
                    .writeTimeout(timeout, TimeUnit.SECONDS)
                    .connectTimeout(timeout, TimeUnit.SECONDS)
                    .build();

            Request request = new Request.Builder().url(wsUrl).build();

            CompletableFuture<String> resultFuture = new CompletableFuture<>();
            StringBuilder responseBuilder = new StringBuilder();

            client.newWebSocket(request, new WebSocketListener() {
                @Override
                public void onOpen(WebSocket webSocket, Response response) {
                    logger.info("WebSocket连接已打开，状态码: {}", response.code());
                    if (response.code() == 101) {
                        JSONObject requestJson = createRequestBody(question, userId);
                        logger.debug("请求体: {}", requestJson.toJSONString());
                        webSocket.send(requestJson.toJSONString());
                    } else {
                        logger.error("WebSocket握手失败，状态码: {}", response.code());
                        resultFuture.completeExceptionally(new RuntimeException("WebSocket握手失败，状态码: " + response.code()));
                        webSocket.close(1000, "握手失败");
                    }
                }

                @Override
                public void onMessage(WebSocket webSocket, String text) {
                    try {
                        logger.debug("收到消息: {}", text);
                        JSONObject response = JSON.parseObject(text);

                        int code = response.getJSONObject("header").getIntValue("code");
                        if (code != 0) {
                            String errorMsg = response.getJSONObject("header").getString("message");
                            logger.error("API返回错误: {} - {}", code, errorMsg);
                            resultFuture.completeExceptionally(new RuntimeException("API错误: " + errorMsg));
                            webSocket.close(1000, "API错误");
                            return;
                        }

                        int status = response.getJSONObject("header").getIntValue("status");

                        if (response.containsKey("payload") && response.getJSONObject("payload").containsKey("choices")) {
                            JSONObject choices = response.getJSONObject("payload").getJSONObject("choices");

                            if (choices.containsKey("text")) {
                                JSONArray textArray = choices.getJSONArray("text");
                                if (textArray != null && !textArray.isEmpty()) {
                                    for (int i = 0; i < textArray.size(); i++) {
                                        String content = textArray.getJSONObject(i).getString("content");
                                        if (content != null && !content.isEmpty()) {
                                            responseBuilder.append(content);
                                        }
                                    }
                                }
                            }
                            // 移除else if (choices instanceof JSONArray)相关代码，因为choices是JSONObject
                        }

                        if (status == 2) {
                            resultFuture.complete(responseBuilder.toString());
                            webSocket.close(1000, "完成");
                        }
                    } catch (Exception e) {
                        logger.error("处理WebSocket消息时出错: {}", e.getMessage(), e);
                        resultFuture.completeExceptionally(e);
                        webSocket.close(1000, "处理消息错误");
                    }
                }

                @Override
                public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                    String errorMsg = "WebSocket连接失败: " + t.getMessage();
                    if (response != null) {
                        errorMsg += ", 状态码: " + response.code();
                    }
                    logger.error(errorMsg, t);

                    if (response != null && response.code() == 401) {
                        resultFuture.complete("AI服务认证失败(401 Unauthorized)，可能原因：\n" +
                                "1. API密钥不正确或已过期\n" +
                                "2. 账户余额不足或调用次数已用完\n" +
                                "3. 讯飞平台账户状态异常\n\n" +
                                "请联系管理员检查API配置。");
                    } else {
                        resultFuture.completeExceptionally(t);
                    }

                    webSocket.close(1000, "连接失败");
                }

                @Override
                public void onClosed(WebSocket webSocket, int code, String reason) {
                    logger.info("WebSocket连接已关闭: {} - {}", code, reason);
                    if (!resultFuture.isDone()) {
                        resultFuture.complete(responseBuilder.toString().isEmpty() ?
                                "抱歉，AI服务暂时不可用，请稍后再试。错误代码: " + code : responseBuilder.toString());
                    }
                }
            });

            try {
                return resultFuture.get(timeout, TimeUnit.SECONDS);
            } catch (Exception e) {
                logger.error("获取AI回答出错: {}", e.getMessage(), e);
                return "抱歉，AI服务暂时不可用，请稍后再试。错误信息: " + e.getMessage();
            }
        } catch (Exception e) {
            logger.error("处理AI问题时发生未预期错误: {}", e.getMessage(), e);
            return "抱歉，AI服务暂时不可用，请稍后再试。错误信息: " + e.getMessage();
        }
    }

    private String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl.replace("wss://", "https://").replace("ws://", "http://"));

        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());

        String signatureOrigin = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";

        logger.debug("签名原始字符串: {}", signatureOrigin);

        // 修改这里：使用"hmacsha256"而不是"HmacSHA256"
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(secretKeySpec);
        byte[] signatureBytes = mac.doFinal(signatureOrigin.getBytes(StandardCharsets.UTF_8));
        String signature = Base64.getEncoder().encodeToString(signatureBytes);

        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                apiKey, "hmac-sha256", "host date request-line", signature);

        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build();

        return httpUrl.toString();
    }

    private JSONObject createRequestBody(String question, String userId) {
        JSONObject requestJson = new JSONObject();

        JSONObject header = new JSONObject();
        header.put("app_id", appId);
        header.put("uid", "session_" + userId + "_" + System.currentTimeMillis());
        requestJson.put("header", header);

        JSONObject parameter = new JSONObject();
        JSONObject chat = new JSONObject();

        String domain = "generalv3";
        if (apiUrl.contains("/v1.1/chat")) {
            domain = "lite";
        } else if (apiUrl.contains("/v3.1/chat")) {
            domain = "generalv3";
        } else if (apiUrl.contains("/chat/pro-128k")) {
            domain = "pro-128k";
        } else if (apiUrl.contains("/v3.5/chat")) {
            domain = "generalv3.5";
        } else if (apiUrl.contains("/chat/max-32k")) {
            domain = "max-32k";
        } else if (apiUrl.contains("/v4.0/chat")) {
            domain = "4.0Ultra";
        }

        chat.put("domain", domain);
        chat.put("temperature", 0.5);
        chat.put("max_tokens", 4096);
        parameter.put("chat", chat);
        requestJson.put("parameter", parameter);

        JSONObject payload = new JSONObject();
        JSONObject message = new JSONObject();
        JSONArray text = new JSONArray();

        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", question);
        text.add(userMessage);

        message.put("text", text);
        payload.put("message", message);
        requestJson.put("payload", payload);

        return requestJson;
    }
}